package com.lagou.parse;

import com.lagou.config.Configuration;
import com.lagou.util.Resources;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created by seemygo on 2020/11/13.
 */
public class XmlConfigBuilder {

    private Configuration configuration=new Configuration();

    public XmlConfigBuilder(Configuration configuration) {

    }

    public Configuration parseXmlConfiguration(InputStream inputStream) throws Exception {
        //第一部分是解析数据库相关配置信息
        Document document=new SAXReader().read(inputStream);
        //<configuration>
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.selectNodes("//property");
        Properties properties=new Properties();
        for (Element node : elements){
            String name = node.attributeValue("name");
            String value = node.attributeValue("value");
            properties.setProperty(name,value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        this.configuration.setDataSource(comboPooledDataSource);

        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for (Element mapperElement : mapperElements) {
            //获取resource 配置的sqlMapper.xml配置路径
            //通过xml文件路径 解析成字节输入流
            String resourcePath = mapperElement.attributeValue("resource");
            InputStream resourcesAsStream = Resources.getResourcesAsStream(resourcePath);
            //第二部分是解析sqlXml相关配置信息
            SqlConfigBuilder sqlConfigBuilder=new SqlConfigBuilder(configuration);
            sqlConfigBuilder.parseSqlConfig(resourcesAsStream);
        }


        return configuration;
    }
}
